﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;
using System.IO;
using HealthManagement.Models;
using com.jwxcd.CommunityDriver;
using PersonalHealth.Data.Model;
using HealthManagement.Common;
using UI.Comm.Common;
using PersonalHealth.Data.IService;
using PersonalHealth.Data.Service;

namespace HealthManagement.Views
{
    /// <summary>
    /// ECG.xaml 的交互逻辑
    /// </summary>
    public partial class ECG : MeasureBase
    {
        MeasureUser user;
        IList<Threshold> thresholds;
        UserPanel parentPage;
        public ECG(MeasureUser user, UserPanel p)
        {
            InitializeComponent();
            this.user = user;
            this.parentPage = p;
            this.Loaded += new RoutedEventHandler(BloodOximeter_Loaded);
        }

        void BloodOximeter_Loaded(object sender, RoutedEventArgs e)
        {
            testStepGrid.Visibility = Visibility.Visible;

            Dispatcher.BeginInvoke(
                new Action(
                  () =>
                  {
                      connectTimer = new DispatcherTimer();
                      connectTimer.Interval = new TimeSpan(10000000);
                      connectTimer.Tick += new EventHandler(connectTimer_Tick);
                      connectSecondsCount = 0;
                      connectTimer.Start();
                  }
                )
            );
            driver.connect();
        }

        DispatcherTimer connectTimer;
        int connectSecondsCount = 0;
        void connectTimer_Tick(object sender, EventArgs e)
        {
            connectSecondsCount++;
            connectDown.Text = (30 - connectSecondsCount).ToString();
            if (connectSecondsCount == 30)
            {
                DispatcherTimer timer = sender as DispatcherTimer;
                timer.Stop();

                OnError("连接设备超时，请返回重试！");
            }
        }

        public override void onDriverConnected(object sender, EventArgs e)
        {
            Thread.Sleep(500);
            Dispatcher.Invoke(new Action(
               () =>
               {
                   if (connectTimer != null)
                       connectTimer.Stop();
                   testStepGrid.Visibility = Visibility.Collapsed;
                   resultStepGrid.Visibility = Visibility.Visible;
                   ecgModel = new ChartModel(120);
                   ecgModel.AxisYMaxValue = 400;
                   ecgModel.AxisYMinValue = -160;
                   ecgModel.YIntercept = 120;
                   ecgModel.AxisYStep = 20;
                   this.DataContext = ecgModel;
                   RadChart1.SamplingSettings.SamplingThreshold = ecgModel.SamplingThreshold;

                   datas.Clear();
               }));

        }

        Queue<int> datas = new Queue<int>();
        ChartModel ecgModel;
        bool isStop = false;
        public override void onMeasure(object sender, MeasureEventArgs e)
        {
            if (!isStop)
            {
                Dispatcher.Invoke(new Action(
                       () =>
                       {
                           if (e.value.ECG == null)
                               return;
                           //如果全部为0直接return
                           bool isAllZero = true;


                           for (int i = 0; i < e.value.ECG.Count; i++)
                           {
                               if (e.value.ECG[i] != 0)
                               {
                                   isAllZero = false;
                                   break;
                               }
                           }
                           if (isAllZero)
                               return;

                           foreach (var data in e.value.ECG)
                               datas.Enqueue(data);
                           if (datas.Count > 120 * 10)
                           {
                               for (int i = 0; i < datas.Count - 120 * 10; i++)
                                   datas.Dequeue();
                           }

                           DateTime now = DateTime.Now;
                           ecgModel.EnqueueValue(e.value.ECG, now);
                           ecgModel.SetUpAxisXRange(now);

                           ecgModel.Data = null;
                           ecgModel.Data = ecgModel.CpuData;

                           if (btnControl.Visibility != Visibility.Visible)
                               btnControl.Visibility = Visibility.Visible;


                       }
                    ));
            }
        }

        private void Control_Click(object sender, RoutedEventArgs e)
        {
            if (tbControl.Text == "停止")
            {
                Save.Visibility = Visibility.Visible;
                ecgModel.Reset();
                isStop = true;

                tbControl.Text = "开始";
            }
            else if (tbControl.Text == "开始")
            {
                Save.Visibility = Visibility.Collapsed;
                isStop = false;
                tbControl.Text = "停止";

                ecgModel.Data = null;

                datas.Clear();
            }
        }

        //保存
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            byte[] obj = Tools.generateEcgDiagram(datas.ToArray(), 120);

            save(obj);
            parentPage.btnStop.IsEnabled = false;
            parentPage.contentBorder.Content = null;
        }

        //取消
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            parentPage.btnStop.IsEnabled = false;
            parentPage.contentBorder.Content = null;
        }

        private object lockObj = new object();
        private bool isUnload = false;
        public override void MeasureBase_Unloaded(object sender, RoutedEventArgs e)
        {
            lock (lockObj)
            {
                if (isUnload)
                {
                    return;
                }
                else
                {
                    if (connectTimer != null)
                        connectTimer.Stop();
                    base.MeasureBase_Unloaded(sender, e);
                    isUnload = true;
                }
            }
          
        }

        private void save(byte[] obj)
        {
            Measure_ECG ecg = new Measure_ECG();
            ecg.UserId = user.Id;
            ecg.EcgDiagram = obj;
            DateTime now = DateTime.Now;
            ecg.MeasureTime = ecg.CreateDate = ecg.ModifyDate = now;
            ecg.EcgDiagramUrl = "";
            ecg.EcgValue = "";
            IMeasure_ECGService ser = new Measure_ECGService();
            ser.Add(ecg);
        }
      
    }
}
